package boardgamer.licensing;

import android.app.Activity;
import android.os.Handler;
import android.provider.Settings;
import com.android.vending.licensing.AESObfuscator;
import com.android.vending.licensing.LicenseChecker;
import com.android.vending.licensing.LicenseCheckerCallback;
import com.android.vending.licensing.ServerManagedPolicy;

import static android.provider.Settings.Secure.ANDROID_ID;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author garysoed
 */
public class Licensing {

  private final Handler handler;
  private final LicenseChecker licenseChecker;
  private final CheckCallback checkCallback;
  
  public Licensing(Activity activity, byte[] salt, String publicKey, CheckCallback checkCallback) {
    this.handler = new Handler();
    this.licenseChecker = new LicenseChecker(
        activity,
        new ServerManagedPolicy(
            activity,
            new AESObfuscator(
                salt,
                activity.getPackageName(),
                Settings.Secure.getString(activity.getContentResolver(), ANDROID_ID))),
        publicKey);
    this.checkCallback = checkNotNull(checkCallback, "checkCallback");
  }

  public void startCheck() {
    licenseChecker.checkAccess(new Callback(handler, checkCallback));
  }

  public void destroy() {
    licenseChecker.onDestroy();
  }

  private static class Callback implements LicenseCheckerCallback {

    private final Handler handler;
    private final CheckCallback checkCallback;

    public Callback(Handler handler, CheckCallback checkCallback) {
      this.handler = checkNotNull(handler, "handler");
      this.checkCallback = checkNotNull(checkCallback, "checkCallback");
    }

    @Override
    public void allow() {
      checkCallback.onAllowed();
    }

    @Override
    public void dontAllow() {
      checkCallback.onDisallowed();
    }

    @Override
    public void applicationError(ApplicationErrorCode errorCode) {
      // TODO: Log error
      dontAllow();
    }
  }

  public interface CheckCallback {

    void onAllowed();

    void onDisallowed();
  }
}
